"""
CSPBuilder plugin

Execute applications from builder.py

Copyright (c) 2008 Rune M. Friborg, runef@diku.dk.
See LICENSE.txt for licensing details (GPLv2).
"""

PLUGIN_NAME = "ExecuteEnv"

import sys
import wx
import time
from subprocess import Popen, PIPE
import thread

from extensions import cspxml
from plugins.builder import *

class PluginExecuteEnv(PluginBUILDER):
	
	def __init__(self, pluginManager):
		PluginBUILDER.__init__(self, pluginManager, PLUGIN_NAME)

		self.time = 0.0
		self.process = None
		
		self.infoCtrl = None
		self.executeButton = None
		self.killButton = None
		self.panel = None


	def _draw_execute_items(self, mainFrame):

		self.panel = wx.Panel(mainFrame.leftPanel, -1)
		sizer = wx.BoxSizer(wx.VERTICAL)

		self.panel.SetAutoLayout(True)
		self.panel.SetSizer(sizer)

		leftSizer = mainFrame.leftPanel.GetSizer()
		leftSizer.Add(self.panel)

		self.executeButton = wx.Button(self.panel, -1, "Execute")
		sizer.Add(self.executeButton, 0, wx.ALIGN_CENTER | wx.ALL, 5)
		self.panel.Bind(wx.EVT_BUTTON, lambda event:self.execute(mainFrame,event), self.executeButton)

		self.infoCtrl = wx.TextCtrl(self.panel, -1, "", size=(125, -1), style=wx.TE_CENTRE | wx.TE_READONLY)
		sizer.Add(self.infoCtrl, 0, wx.ALIGN_CENTER | wx.ALL, 5)

		self.killButton = wx.Button(self.panel, -1, "Kill!")
		sizer.Add(self.killButton, 0, wx.ALIGN_CENTER | wx.ALL, 5)
		self.panel.Bind(wx.EVT_BUTTON, self.kill, self.killButton)
		self.killButton.Enable(False)


	def kill(self, event):
		try:
			self.infoCtrl.SetValue(' Killing pid: ' + str(self.process.pid))
			print 'Killing process: ',self.process.pid
			self.process.kill()
		except:
			# try using kill -9
			if sys.platform == 'darwin' or sys.platform == 'linux2':
				cmd = 'kill -9 '+ str(self.process.pid)
				kill_process = Popen(cmd, shell=True, bufsize=0,
						     stdin=None, stdout=None, close_fds=True)
				kill_process.wait()
			else:
				print 'Killing processes needs Python 2.6 or Unix'
			
		

	""" Update status in builder.py"""
	def status_thread(self):
		self.infoCtrl.SetValue(' Running ')
					
		while self.process.poll() == None:
			self.panel.Refresh()
			time.sleep(0.1)
			self.time += 0.1
		self.killButton.Enable(False)
		self.executeButton.Enable(True)
		self.infoCtrl.SetValue(' Stopped ')


	def execute(self, mainFrame, event):

		# ask user
		mainFrame.askIfUserWantsToSave('executing')

		#if mainFrame.fileName == None:
		if not mainFrame.compName:
			self.infoCtrl.SetValue(' No file! ')
			return

      	# init
		self.infoCtrl.SetValue('')
		self.executeButton.Enable(False)
		self.killButton.Enable(True)
		self.time = 0.0
		
		
		# CSPBuilder application
		exeVersion = str(mainFrame.compVersion)
		if mainFrame.editVersion:
			exeVersion = 'e' + exeVersion
			
		cmd = sys.path[0] + '/execute.py "'+ mainFrame.compPath + '" -v ' + exeVersion
		print cmd
		self.process = Popen(cmd, shell=True, bufsize=0,
			  stdin=None, stdout=None, close_fds=True)
		
		# Start status thread
		thread.start_new_thread(self.status_thread, ())
		
	
		

def load(pluginManager):
	p = PluginExecuteEnv(pluginManager)
	p.addLeftBarElement(p._draw_execute_items)
	pluginManager.addPlugin(p)
